//
//  BIDDetailEmailFromInboxViewController.m
//  shangwuting
//
//  Created by mal on 13-12-25.
//  Copyright (c) 2013年 mal. All rights reserved.
//

#import "BIDDetailEmailFromInboxViewController.h"
#import "BIDShowPhotoView.h"
#import "BIDDownloadFile.h"
#import "BIDShowDocView.h"
#import "BIDTransmitEmailViewController.h"
#import "BIDAccessoryListCanOpenViewController.h"
#import "BIDMenuView.h"
#import "BIDReplyView.h"

static const CGFloat CELL_HEIGHT = 20.0f;

//详情
static NSString *strDetailEmailURL = @"emailReplyAndroid!toReadInbox.action";
//下载
static NSString *strDownloadURL = @"emailAndroid!download.action";
//删除邮件
static NSString *strDeleteURL = @"emailReplyAndroid!dropInbox.action";
//回复
static NSString *strReplyURL = @"emailReplyAndroid!reply.action";

@interface BIDDetailEmailFromInboxViewController ()<BIDShowPhotoViewDelegate, BIDDownloadFileDelegate, BIDMenuViewDelegate, BIDReplyViewDelegate>
{
    BIDMenuView *_menuView;
    BOOL _bShowMenu;
    BIDReplyView *_replyView;
}
@end

@implementation BIDDetailEmailFromInboxViewController
@synthesize titleLabel;
@synthesize senderLabel;
@synthesize timeLabel;
@synthesize contentLabel;
@synthesize showPhotoView;
@synthesize myTabelView;
@synthesize confirmBtn;
@synthesize replyBtn;
@synthesize replyTF;
@synthesize myScrollView;
@synthesize lineLabel1;
@synthesize lineLabel2;
@synthesize docsArr;
@synthesize photosArr;
@synthesize photosDataArr;
@synthesize dataArr;
@synthesize emailId;
@synthesize downloadFile;
@synthesize showDocView;
@synthesize willOpenFileName;
@synthesize creatorId;
@synthesize creatorName;
@synthesize deleteId;
@synthesize bgImgView1;
@synthesize bReaded;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = @"邮件详情";
    // Do any additional setup after loading the view from its nib.
    photosDataArr = [[NSMutableArray alloc] initWithCapacity:1];
    //
    [contentLabel setBackgroundColor:[UIColor clearColor]];
    [contentLabel setFont:[UIFont systemFontOfSize:[AppDelegate getFontSize]]];
    contentLabel.numberOfLines = 0;
    
    //
    downloadFile = [[BIDDownloadFile alloc] init];
    downloadFile.delegate = self;
    downloadFile.saveDirectory = @"downloads/doc/";
    [downloadFile initData];
    
    //文档视图
    showDocView = [[BIDShowDocView alloc] init];
    //
    CGSize screenSize = [UIScreen mainScreen].bounds.size;
    _replyView = [[BIDReplyView alloc] initWithFrame:CGRectMake(0, -screenSize.height, 0, 0)];
    _replyView.titleLabel.text = @"写回复";
    _replyView.delegate = self;
    //
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"icon_more.png"] style:UIBarButtonItemStylePlain target:self action:@selector(functionHandler)];
    
    [self loadData];
}

- (void)viewWillAppear:(BOOL)animated
{
    [[UIApplication sharedApplication] setStatusBarHidden:NO];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    titleLabel = nil;
    senderLabel = nil;
    timeLabel = nil;
    contentLabel = nil;
    showPhotoView = nil;
    myTabelView = nil;
    confirmBtn = nil;
    replyTF = nil;
    replyBtn = nil;
    docsArr = nil;
    photosArr = nil;
    dataArr = nil;
    showDocView = nil;
}

- (void)viewWillDisappear:(BOOL)animated
{
}

- (void)initLayout
{
    //调整布局
    CGSize screenSize = [UIScreen mainScreen].bounds.size;
    CGRect ownFrame = self.view.frame;
    ownFrame.size.height = screenSize.height-64;
    self.view.frame = ownFrame;
    CGRect frame = replyTF.frame;
    frame.origin.y = ownFrame.size.height-8-frame.size.height;
    replyTF.frame = frame;
    [replyTF setBackgroundColor:[UIColor clearColor]];
    frame = replyBtn.frame;
    frame.origin.y = ownFrame.size.height-8-frame.size.height;
    replyBtn.frame = frame;
    
    frame = confirmBtn.frame;
    frame.origin.y = ownFrame.size.height-46-frame.size.height;
    confirmBtn.frame = frame;
    
    bgImgView1.frame = myTabelView.frame;
    myTabelView.backgroundView = bgImgView1;
    
    //
    CGFloat myScrollViewPosY = 68.0f;
    CGRect myScrollViewFrame = CGRectMake(0, myScrollViewPosY, ownFrame.size.width, ownFrame.size.height-myScrollViewPosY-8);
    myScrollView.directionalLockEnabled = YES;
    myScrollView = [[UIScrollView alloc] initWithFrame:myScrollViewFrame];
    [self.view addSubview:myScrollView];
    //line1
    CGRect lineFrame = lineLabel1.frame;
    lineFrame.origin.y = 0.0f;
    lineLabel1.frame = lineFrame;
    [myScrollView addSubview:lineLabel1];
    //
    CGSize contentLabelSize = [contentLabel.text sizeWithFont:contentLabel.font constrainedToSize:CGSizeMake(contentLabel.frame.size.width, MAXFLOAT) lineBreakMode:NSLineBreakByWordWrapping];
    CGRect contentLabelFrame = contentLabel.frame;
    contentLabelFrame.origin.y = 3.0f;
    contentLabelFrame.size.height = contentLabelSize.height>62?contentLabelSize.height+1:62;
    contentLabel.frame = contentLabelFrame;
    [myScrollView addSubview:contentLabel];
    //
    lineFrame.origin.y = contentLabel.frame.origin.y + contentLabel.frame.size.height + 2;
    lineLabel2.frame = lineFrame;
    [myScrollView addSubview:lineLabel2];
    //
    //设置拍照视图
    int interval = 2;
    int intervalFromPhotoViewToTextView = 15;
    CGSize ownSize = self.view.frame.size;
    CGSize showPhotoViewSize = CGSizeMake(ownSize.width-interval*2, 100);
    CGRect showPhotoViewFrame = CGRectMake(interval, contentLabel.frame.origin.y+contentLabel.frame.size.height+intervalFromPhotoViewToTextView, showPhotoViewSize.width, showPhotoViewSize.height);
    showPhotoView = [[BIDShowPhotoView alloc] initWithFrame:showPhotoViewFrame];
    showPhotoView.photoCount = 3;
    showPhotoView.addPhotoBtn.hidden = YES;
    showPhotoView.bCanSave = YES;
    showPhotoView.bNeedScale = YES;
    [myScrollView addSubview:showPhotoView];
    showPhotoView.delegate = self;
    
    //附件
    frame = myTabelView.frame;
    frame.origin.y = showPhotoViewFrame.origin.y + showPhotoViewFrame.size.height + 3;
    frame.size.height = docsArr.count * CELL_HEIGHT;
    myTabelView.frame = frame;
    [myScrollView addSubview:myTabelView];
    
    //
    CGFloat scrollContentHeight = myTabelView.frame.origin.y + myTabelView.frame.size.height + 3;
    if(scrollContentHeight>myScrollView.frame.size.height)
    {
        CGSize contentSize = CGSizeMake(ownFrame.size.width, scrollContentHeight);
        [myScrollView setContentSize:contentSize];
    }
}

//加载数据
- (void)loadData
{
    NSString *strURL = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getServerAddr], strDetailEmailURL];
    NSString *strPost = [[NSString alloc] initWithFormat:@"emailId=%@&id=%@", emailId, deleteId];
    [self sendHttpRequestWithURL:strURL postData:strPost withCompletion:^(NSDictionary *responseDic, NSString *errMsg){
        if(responseDic)
        {
            if(!bReaded)
            {
                [UIApplication sharedApplication].applicationIconBadgeNumber--;
            }
            //
            NSDictionary *emailDictionary = [responseDic objectForKey:@"email"];
            creatorId = [emailDictionary objectForKey:@"createId"];
            creatorName = [emailDictionary objectForKey:@"createName"];
            NSString *str = [emailDictionary objectForKey:@"title"];
            NSRange range = [str rangeOfString:@"|"];
            if(range.location==NSNotFound)
            {
                
            }
            else
            {
                str = [str substringFromIndex:range.location+1];
            }
            titleLabel.text = str;
            senderLabel.text = [[NSString alloc] initWithFormat:@"发送人:%@",[emailDictionary objectForKey:@"createName"]];
            timeLabel.text = [[NSString alloc] initWithFormat:@"发送时间:%@", [emailDictionary objectForKey:@"time"]];
            contentLabel.text = [emailDictionary objectForKey:@"content"];
            
            //附件
            docsArr = [[NSMutableArray alloc] initWithArray:[responseDic objectForKey:@"others"]];
            [self initLayout];
            if(docsArr.count==0) myTabelView.hidden = YES;
            else
            {
                [myTabelView reloadData];
            }
            
            //图片
            photosArr = [[NSMutableArray alloc] initWithArray:[responseDic objectForKey:@"photos"]];
            [self loadPhotos];
        }
    }];
}

//加载图片并显示
- (void)loadPhotos
{
    //NSMutableArray *idsArr;
    if(photosArr.count>0)
    {
        [self showSpinnerView];
        //idsArr = [[NSMutableArray alloc] initWithCapacity:photosArr.count];
        dispatch_group_t group = dispatch_group_create();
        for(int i=0; i<photosArr.count; i++)
        {
            NSDictionary *dictionary = [photosArr objectAtIndex:i];
            dispatch_group_async(group, dispatch_get_global_queue(0, 0), ^{
                NSString *strId = [dictionary objectForKey:@"id"];
                NSString *strURL = [[NSString alloc] initWithFormat:@"%@/%@?emailId=%@", [AppDelegate getServerAddr], strDownloadURL, strId];
                NSString *strFileName = [dictionary objectForKey:@"fileName"];
                NSMutableData *data = [NSMutableData data];
                [BIDDataCommunication getDataFromNet:strURL data:data];
                NSDictionary *dictionary1 = [[NSDictionary alloc] initWithObjectsAndKeys:strFileName, @"fileName", data, @"data", nil];
                [photosDataArr addObject:dictionary1];
            });
        }
        dispatch_group_notify(group, dispatch_get_global_queue(0, 0), ^{
            dispatch_async(dispatch_get_main_queue(), ^{
                [self hideSpinnerView];
                for(int i=0; i<photosDataArr.count; i++)
                {
                    NSDictionary *dataDictionary = [photosDataArr objectAtIndex:i];
                    NSData *data = [dataDictionary objectForKey:@"data"];
                    UIImage *img = [UIImage imageWithData:data];
                    NSLog(@"%f,%f", img.size.width, img.size.height);
                    [self.showPhotoView addPhoto:img];
                }
                
            });
        });
    }
    else
    {
        //当没有图片时，展示附件的列表需要改变下位置
        showPhotoView.hidden = YES;
        CGRect frame = showPhotoView.frame;
        CGRect tableViewFrame = myTabelView.frame;
        tableViewFrame.origin.y = frame.origin.y;
        tableViewFrame.size.height = docsArr.count * CELL_HEIGHT;
        myTabelView.frame = tableViewFrame;
    }
}

/**
 *  更多
 */
- (void)functionHandler
{
    //弹出菜单
    if(!_menuView)
    {
        NSArray *menuNameArr = @[@"已下附件", @"转发邮件", @"快捷回复", @" 回复        ", @" 删除        "];
        CGSize screenSize = [UIScreen mainScreen].bounds.size;
        //menuWidth,menuHeight,triangleWidth,triangleHeight,triangleToRight
        BIDMenuAttribute menuAttribute = {120, 5, 10, 15, 14};
        int menuViewPosX = screenSize.width - 26 - (menuAttribute.menuWidth-menuAttribute.triangleToRight-menuAttribute.triangleWidth/2);
        int menuViewPosY = 2;
        _menuView = [[BIDMenuView alloc] initWithFrame:CGRectMake(menuViewPosX, menuViewPosY, menuAttribute.menuWidth, menuAttribute.menuHeight) menuNameArr:menuNameArr imgNameArr:nil menuAttribute:menuAttribute];
        _menuView.delegate = self;
    }
    if(!_bShowMenu)
    {
        _bShowMenu = YES;
        [self.view addSubview:_menuView];
    }
    else
    {
        _bShowMenu = NO;
        [UIView animateWithDuration:1.0f animations:^{
            //_menuView.transform = CGAffineTransformMakeScale(0.5f, 0.5f);
        } completion:^(BOOL bFinished){
            if(bFinished)
            {
                [_menuView removeFromSuperview];
            }
        }];
    }
}

//删除邮件
- (void)deleteEmail
{
    NSString *strRequestURL = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getServerAddr], strDeleteURL];
    NSString *strPost = [[NSString alloc] initWithFormat:@"ids=%@", deleteId];
    [self sendHttpRequestWithURL:strRequestURL postData:strPost withCompletion:^(NSDictionary *responseDic, NSString *errMsg){
        if(responseDic)
        {
            NSNumber *value = [responseDic objectForKey:@"isSuccess"];
            if([value intValue]==1)
            {
                [BIDGlobalMethods showAlertView:@"删除成功" buttonTitle:@"关闭" delegate:self tag:1];
            }
            else
            {
                [BIDGlobalMethods showAlertView:@"删除失败" buttonTitle:@"关闭" delegate:nil tag:0];
            }
        }
    }];
}

//回复邮件
- (void)replyEmail:(NSString *)strContent
{
    NSString *strName = [AppDelegate getUserTrueName];
    NSString *strTitle = [[NSString alloc] initWithFormat:@"%@回复邮件|%@", strName, titleLabel.text];
    NSString *strRequestURL = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getServerAddr], strReplyURL];
    NSString *strPost = [[NSString alloc] initWithFormat:@"userId=%@&receiveId=%@&title=%@&content=%@", [AppDelegate getUserId], creatorId, strTitle, strContent];
    [self sendHttpRequestWithURL:strRequestURL postData:strPost withCompletion:^(NSDictionary *responseDic, NSString *errMsg){
        if(responseDic)
        {
            NSNumber *value = [responseDic objectForKey:@"isSuccess"];
            if([value intValue]==1)
            {
                [BIDGlobalMethods showAlertView:@"回复成功" buttonTitle:@"关闭" delegate:nil tag:0];
            }
            else
            {
                [BIDGlobalMethods showAlertView:@"回复失败" buttonTitle:@"关闭" delegate:nil tag:0];
            }
        }
    }];
}

//确认收到
- (IBAction)confirmBtnHandler:(id)sender
{
    NSString *strContent = @"邮件已收到";
    [self replyEmail:strContent];
}

//回复
- (IBAction)replyBtnHandler:(id)sender
{
    NSString *strContent = replyTF.text;
    strContent = strContent.length>0?strContent:@"";
    [self replyEmail:strContent];
}

//
- (IBAction)tfEditEnd:(id)sender
{
    [replyTF resignFirstResponder];
}

//判断文件是否已下载过
- (BOOL)isFileExist:(NSString *)fileName
{
    NSFileManager *fileManager = [[NSFileManager alloc] init];
    NSArray *urls = [fileManager URLsForDirectory:NSLibraryDirectory inDomains:NSUserDomainMask];
    if(urls.count>0)
    {
        NSError *err;
        NSURL *libraryURL = urls[0];
        NSURL *downloadURL = [libraryURL URLByAppendingPathComponent:@"downloads/doc/" isDirectory:YES];
        if([fileManager createDirectoryAtURL:downloadURL withIntermediateDirectories:YES attributes:nil error:&err])
        {
            NSArray *files = [fileManager contentsOfDirectoryAtURL:downloadURL includingPropertiesForKeys:nil options:0 error:&err];
            for(NSURL *fileURL in files)
            {
                NSString *strFileName = [fileURL lastPathComponent];
                if([fileName isEqualToString:strFileName])
                {
                    return YES;
                }
            }
            return NO;
        }
    }
    return NO;
}

#pragma mark - BIDReplyViewDelegate
- (void)replyWithContent:(NSString *)replyContent
{
    replyContent = replyContent.length>0?replyContent:@"";
    [self replyEmail:replyContent];
}

#pragma mark - BIDMenuViewDelegate
- (void)selectMenuAtIndex:(int)index
{
    _bShowMenu = NO;
    switch(index)
    {
        case 0:
        {
            //已下附件
            BIDAccessoryListCanOpenViewController *accessoryListViewController = [[BIDAccessoryListCanOpenViewController alloc] init];
            [self.navigationController pushViewController:accessoryListViewController animated:YES];
        }
            break;
        case 1:
        {
            //转发邮件
            BIDTransmitEmailViewController *transmitEmailViewController = [[BIDTransmitEmailViewController alloc] initWithNibName:@"BIDTransmitEmailViewController" bundle:nil];
            transmitEmailViewController.emailId = emailId;
            [self.navigationController pushViewController:transmitEmailViewController animated:YES];
        }
            break;
        case 2:
        {
            //快捷回复
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"您确定回复此通知\"确认收到\"吗?" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            alertView.tag = 2;
            [alertView show];
        }
            break;
        case 3:
        {
            //回复
            [_replyView showTheView];
        }
            break;
        case 4:
        {
            //删除
            [self deleteEmail];
        }
            break;
    }
}

#pragma mark - BIDDownloadFileDelegate
- (void)toOpenDoc
{
    [showDocView openDoc:willOpenFileName];
}

#pragma mark - BIDShowPhotoViewDelegate
- (void)changeStatusForStatusBar:(NSInteger)type
{
    if(type==1)
    {
        [[UIApplication sharedApplication] setStatusBarHidden:NO];
    }
    else
    {
        [[UIApplication sharedApplication] setStatusBarHidden:YES];
    }
}

#pragma mark UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [docsArr count];
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"identifier";
    NSUInteger row = [indexPath row];
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if(!cell)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    NSDictionary *dictionary = [docsArr objectAtIndex:row];
    NSString *strFileName = [dictionary objectForKey:@"fileName"];
    NSString *strFileSize = [dictionary objectForKey:@"size"];
    strFileSize = [[NSString alloc] initWithFormat:@"(%@)", strFileSize];
    NSUInteger len1 = strFileName.length;
    NSUInteger len2 = strFileSize.length;
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:[[NSString alloc] initWithFormat:@"%@%@", strFileName, strFileSize]];
    [str addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(0, len1)];
    [str addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:47.0f/255.0f green:132.0f/255.0f blue:61.0f/255.0f alpha:1.0f] range:NSMakeRange(len1, len2)];
    [str addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInt:NSUnderlineStyleSingle] range:NSMakeRange(0, len1)];
    cell.textLabel.attributedText = str;
    cell.textLabel.font = [UIFont systemFontOfSize:13.0f];
    [cell setBackgroundColor:[UIColor clearColor]];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSUInteger row = [indexPath row];
    NSDictionary *dictionary = [self.docsArr objectAtIndex:row];
    NSString *strFileName = [dictionary objectForKey:@"fileName"];
    willOpenFileName = strFileName;
    
    if([self isFileExist:strFileName])
    {
        [showDocView openDoc:strFileName];
    }
    else
    {
        //先下载
        NSString *accessoryId = [dictionary objectForKey:@"id"];
        NSString *downloadURL = [[NSString alloc] initWithFormat:@"%@/%@?emailId=%@", [AppDelegate getServerAddr], strDownloadURL, accessoryId];
        downloadFile.fileName = strFileName;
        [downloadFile downloadFile:downloadURL];
    }
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return CELL_HEIGHT;
}

#pragma mark UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(alertView.tag==2)
    {
        //快捷回复
        [self replyEmail:@"确认收到"];
    }
    else if (alertView.tag==1)
    {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

@end
